package com.cxx.food.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxx.food.constant.BizType;
import com.cxx.food.entity.FavouriteRecord;
import com.cxx.food.mapper.FavouriteRecordMapper;
import com.cxx.food.service.FavouriteService;
import com.cxx.framework.web.CustomException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


@Service
public class FavouriteServiceImpl implements FavouriteService {
    @Resource
    private FavouriteRecordMapper favouriteRecordMapper;


    @Override
    public Boolean addFavourite(BizType type, Long subjectId) {
        LambdaQueryWrapper<FavouriteRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavouriteRecord::getSubjectId, subjectId).eq(FavouriteRecord::getCreateBy, StpUtil.getLoginIdAsString());
        FavouriteRecord favourite = favouriteRecordMapper.selectOne(queryWrapper);

        if (favourite != null) {
            throw new CustomException("已经收藏了");
        }

        FavouriteRecord newFavourite = new FavouriteRecord();
        newFavourite.setType(type.getCode());
        newFavourite.setSubjectId(subjectId);
        return favouriteRecordMapper.insert(newFavourite) == 1;
    }

    @Override
    public Boolean deleteFavourite(Long subjectId) {
        LambdaQueryWrapper<FavouriteRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FavouriteRecord::getSubjectId, subjectId).eq(FavouriteRecord::getCreateBy, StpUtil.getLoginIdAsString());
        FavouriteRecord favourite = favouriteRecordMapper.selectOne(queryWrapper);

        if (favourite == null) {
            throw new CustomException("该记录不存在");
        }

        return favouriteRecordMapper.deleteById(favourite) == 1;
    }
}
